<?php
namespace app\paper\service;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

class ExportExcelService
{
    public function getExcel($expTitle, $expCellName, $expTableData, $str = "",$uid=0)
    {
//        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
//        $fileName = $expTitle . date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $common = $str;
        $objPHPExcel = new Spreadsheet();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $common);

        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
        }
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), ' ' . $expTableData[$i][$expCellName[$j][0]]);

            }
        }
        foreach ($cellName as $value) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($value)->setWidth(20);

        }
        $styleArryBody = [
            "alignment"=>[
                'horizontal'=> Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $objPHPExcel->getActiveSheet()->getStyle('A1:' . $cellName[$cellNum - 1] . '1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
        ob_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $expTitle . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
        $filename = "{$uid}.xlsx";
        $filepath=app()->getRootPath() . "public/storage/report/".$filename;
        $objWriter->save($filepath);
        return ['filename'=>$filename,'filepath'=>$filepath];
//        $objPHPExcel->disconnectWorksheets();
//        unset($objPHPExcel);
       // exit();
    }
}